package com.lee.auth.security.filter;

import com.lee.auth.security.context.AuthContext;
import com.lee.auth.security.context.AuthContextHolder;
import com.lee.auth.security.token.TokenPayloadOuter.TokenPayload;
import com.lee.auth.security.token.TokenService;
import lombok.AllArgsConstructor;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author Lee HN
 * @date 2021/3/24 10:04
 */
@AllArgsConstructor
public class TokenFilter implements Filter {

    private final TokenService tokenService;

    private static final String TOKEN_NAME = "Authorization";

    private static final String TOKEN_PREFIX = "Bearer ";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest res = (HttpServletRequest) request;
        String header = res.getHeader(TOKEN_NAME);
        AuthContext authContext;
        if (StringUtils.hasLength(header) && header.startsWith(TOKEN_PREFIX)) {
            String token = header.substring(TOKEN_PREFIX.length());
            TokenPayload payload = tokenService.parseAccessToken(token);
            authContext = AuthContext.of(payload);
        } else authContext = null;
        AuthContextHolder.setAuthContext(authContext);
        chain.doFilter(request, response);
    }

}
